import requests
import urllib.request
import uuid
from pyquery import PyQuery as pq

def parseIndex(index_url):
    """ 解析主页
    :index_url: 主页 url
    :returns: pq 对象

    """
    response = session.get(url = index_url,  headers = headers)
    doc = pq(response.text)
    return doc
    
def download_code(url):
    """下载验证码图片
    :returns: TODO

    """
    filename = 'codes/' + str(uuid.uuid1()) + '.png'
    #  urllib.request.urlretrieve(url, 'codes/' + str(uuid.uuid1()) + '.png')
    # 因为登录验证码需要在同一个会话中才有效, 所以不能用上面的方式.
    resp_img = session.get(url = url, headers = headers)
    with open(filename, 'wb') as fp:
        fp.write(resp_img.content)


def main():
    """主函数
    :returns: None

    """
    index_url = 'http://yun.zjer.cn/index.php'
    doc = parseIndex(index_url)
    code_url = doc('#cimage_portal').attr('src')
    download_code(code_url)

headers = {
    'Accept':
    'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    #  'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Cache-Control': 'max-age=0',
    'Connection': 'keep-alive',
    # 'Cookie': 'ck=ecf90c3e10d32c5f27ff33036cbca6711544056529;sto-id-20480=GNAIBIKMFAAA;UM_distinctid=16780f0e9441b9-0c7bdc96d6e0b2-6313363-1fa400-16780f0e945730;_c90ac=http://10.42.113.251:10000; PHPSESSID=22b7b55kk1d8q0ib2r0k904b36;CNZZDATA1253683400=1669615480-1544051592-%7C1545090982',
    'Host': 'yun.zjer.cn',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
        AppleWebKit/537.36(KHTML, like Gecko) \
        Chrome/70.0.3538.110 Safari/537.36'
}
session = requests.Session()

if __name__ == "__main__":
    main()

